package com.xspace.android.imcommon.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;
import android.util.Log;

import com.xspace.android.imcommon.entity.MucChatMsgBean;
import com.xspace.android.imcommon.entity.MucRoomBean;

import java.util.ArrayList;

/**
 * 联盟圈群聊消息表
 * 
 * @author Administrator
 * 
 */
public class MucChatMessageDB extends BaseDb {

	public static final String TAG = "MucChatMessageDB";
	  /**圈子**/
    public static final String PlatForm_Circle="ChatClient_circle_xmpp";
    /**群组**/
    public static final String PlatForm_Group="ChatClient_group_xmpp";
	/**
	 * _id
	 */
	public static final String _ID = "_id";
	/**
	 * 内容
	 */
	public static final String COLOUMN_CONTENT = "content";
	/**
	 * 最新内容类型 0：文本 1、图片 2、语音 3、视频
	 */
	public static final String COLOUMN_CONTENT_TYPE = "content_type";
	/**
	 * 消息发送时间
	 */
	public static final String COLOUMN_SEND_TIME = "send_time";
	/**
	 * 插入时间
	 */
	public static final String COLOUMN_INSERT_TIME = "insert_time";
	/**
	 * 消息状态 0：发送中 1:发送成功 2 发送失败,3 接收
	 */
	public static final String COLOUMN_STATUS = "status";
	/**
	 * 消息状态 0：未读 1:已读
	 */
	public static final String COLOUMN_READ = "read";
	/**
	 * 发送消息的barejid
	 */
	public static final String COLOUMN_BAREJID = "barejid";
	/**
	 * 消息的uuid
	 */
	public static final String COLOUMN_UUID = "uuid";
	/**
	 * 推送消息所属人name
	 */
	public static final String COLOUMN_SENDER = "sendName";
	public static final String COLOUMN_RoomName = "room";
	public static final String COLOUMN_ROOMID = "roomid";
	public static final String COLOUMN_PlatForm = "platform";
	/**
	 * 错误码
	 */
	public static final String COLOUMN_ERRORCODE = "errorCode";
	/**
	 * 错误消息
	 */
	public static final String COLOUMN_ERRORMSG = "errorMsg";
	public static final String TABLE_NAME = "MUC_CHAT_MSG";
	/**
	 * 图片本地存储路径
	 */
	public static final String COLOUMN_IMGPATH = "imgPath";
	public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
			+ " (" + _ID + " INTEGER primary key, " + COLOUMN_CONTENT
			+ " CHAR(1000)," + COLOUMN_CONTENT_TYPE + " INTEGER,"
			+ COLOUMN_SEND_TIME + " CHAR(128)," + COLOUMN_INSERT_TIME
			+ " CHAR(128)," + COLOUMN_STATUS + " INTEGER," + COLOUMN_READ
			+ " INTEGER," + COLOUMN_BAREJID + " CHAR(128)," + COLOUMN_UUID
			+ " CHAR(128), " + COLOUMN_SENDER + " CHAR(128)," + COLOUMN_ROOMID
			+ " CHAR(128)," + COLOUMN_RoomName + " CHAR(128), "
			+ COLOUMN_PlatForm + " CHAR(128), "
			+ COLOUMN_ERRORCODE + " CHAR(128)," + COLOUMN_ERRORMSG
			+ " CHAR(128)," + COLOUMN_IMGPATH + " CHAR(128))";

	@Override
	String getTableName() {
		return TABLE_NAME;
	}
    public MucChatMessageDB(Context context){
    	super(context);
    }
	/**
	 * 保存消息数据
	 * 
	 * @param city
	 * @return
	 */
	public int insertOrUpdateMsg(MucChatMsgBean chatMsgBean) {
		Log.d(TAG, "insertOrUpdateMsg()... received message: " + chatMsgBean);

		ContentValues values = new ContentValues();
		values.put(COLOUMN_BAREJID, chatMsgBean.fromUserId);
		values.put(COLOUMN_CONTENT, chatMsgBean.mContent);
		values.put(COLOUMN_CONTENT_TYPE, chatMsgBean.mContentType);
		values.put(COLOUMN_INSERT_TIME, chatMsgBean.mInsertTime);
		values.put(COLOUMN_SENDER, chatMsgBean.mUserName);
		values.put(COLOUMN_RoomName, chatMsgBean.roomName);
		values.put(COLOUMN_ROOMID, chatMsgBean.roomID);
		values.put(COLOUMN_SEND_TIME, chatMsgBean.mSendTime);
		values.put(COLOUMN_STATUS, chatMsgBean.mStatus);
		values.put(COLOUMN_READ, chatMsgBean.mRead);
		values.put(COLOUMN_UUID, chatMsgBean.mUUID);
		values.put(COLOUMN_ERRORCODE, chatMsgBean.errorCode);
		values.put(COLOUMN_ERRORMSG, chatMsgBean.errorMsg);
		values.put(COLOUMN_IMGPATH, chatMsgBean.imgPath);
		String platform=chatMsgBean.mPlatForm;
		if("0".equals(chatMsgBean.mPlatForm)){
			platform=PlatForm_Circle;
		}
		else if("1".equals(chatMsgBean.mPlatForm)){
			platform=PlatForm_Group;
		}
		values.put(COLOUMN_PlatForm, platform);
		System.out.println("------------------------chatMsgBean.fromUser:"
				+ chatMsgBean.fromUserId);
		String sql = "select * from " + TABLE_NAME + " where "
				+ COLOUMN_SEND_TIME + " = '" + chatMsgBean.mSendTime + "'";
		Cursor cursor = null;
		try {
			long rowId = -1;
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				rowId = db.update(TABLE_NAME, values, COLOUMN_SEND_TIME + "=?",
						new String[] { chatMsgBean.mSendTime });
			} else {
				rowId = db.insert(TABLE_NAME, null, values);
				Log.e(TAG, "insertOrUpdateMsg()... insert rowId: " + rowId);
			}
			return (int) rowId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			closeDbAndCursor(cursor);
		}
	}

	public int queryUnReadCount(String groupid) {
		int count = 0;
		Cursor cursor=null;
		try {
			checkDb();
			String sql="select count(*) from "+TABLE_NAME+" where "+COLOUMN_READ+"=? and "+COLOUMN_ROOMID+"=?";
		    cursor=db.rawQuery(sql, new String[]{String.valueOf(0),groupid});
		    if(cursor.getCount()>0){
		    	cursor.moveToFirst();
		    	count=cursor.getInt(0);
		    }
		    Log.e(TAG, "queryUnreadCount()... count: " + count);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeDbAndCursor(cursor);
		}
		return count;

	}

	// 修改信息状态
	public boolean updateMsg(MucChatMsgBean chatMsgBean) {
		try {
			checkDb();
			ContentValues values = new ContentValues();
			values.put(COLOUMN_BAREJID, chatMsgBean.fromUserId);
			values.put(COLOUMN_CONTENT, chatMsgBean.mContent);
			values.put(COLOUMN_CONTENT_TYPE, chatMsgBean.mContentType);
			values.put(COLOUMN_INSERT_TIME, chatMsgBean.mInsertTime);
			values.put(COLOUMN_SENDER, chatMsgBean.mUserName);
			if (!TextUtils.isEmpty(chatMsgBean.roomName)) {
				values.put(COLOUMN_RoomName, chatMsgBean.roomName);
			}
			values.put(COLOUMN_SEND_TIME, chatMsgBean.mSendTime);
			values.put(COLOUMN_STATUS, chatMsgBean.mStatus);
			values.put(COLOUMN_READ, chatMsgBean.mRead);
			values.put(COLOUMN_UUID, chatMsgBean.mUUID);
			values.put(COLOUMN_ERRORCODE, chatMsgBean.errorCode);
			values.put(COLOUMN_ERRORMSG, chatMsgBean.errorMsg);
			values.put(COLOUMN_IMGPATH, chatMsgBean.imgPath);
			int num = db.update(TABLE_NAME, values, COLOUMN_SEND_TIME + "=?",
					new String[] { chatMsgBean.mSendTime + "" });
			Log.d(TAG, "updateMsg data effected number:" + num);
			return (num > 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 修改未读消息状态
	 * @param groupid
	 * @param statu 0未读 1已读
	 * @return
	 */
	public boolean updateMsgUnReadStatu(String groupid, int statu) {
		try {
			checkDb();
			ContentValues cv = new ContentValues();
			cv.put(COLOUMN_READ, statu);
			int num = db.update(TABLE_NAME, cv,COLOUMN_ROOMID + "=?",
					new String[] { groupid });
			Log.d(TAG, "updateMsgUnRead affect number:" + num);
			return (num > 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public ArrayList<MucChatMsgBean> queryRoomMsgs(String roomid) {
		ArrayList<MucChatMsgBean> chatMsgs = new ArrayList<MucChatMsgBean>();
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_ROOMID
				+ "=?  order by " + _ID + " desc";
		Log.d(TAG, "queryChatMsgs()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, new String[]{roomid});
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToLast();
				for (int i = cursor.getCount() - 1; i >= 0; i--) {
					cursor.moveToPosition(i);
					MucChatMsgBean entity = parseCursor(cursor);
					Log.d(TAG, "roomid... " + roomid+" id:"+entity._id+ " content:"+entity.mContent);
					chatMsgs.add(entity);
				}
			}
			return chatMsgs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeDbAndCursor(cursor);
		}
	}
	public ArrayList<MucChatMsgBean> queryAllRoomMsgs() {
		ArrayList<MucChatMsgBean> chatMsgs = new ArrayList<MucChatMsgBean>();
		String sql = "select * from " + TABLE_NAME + "  order by " + _ID + " desc";
		Log.d(TAG, "queryChatMsgs()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToLast();
				for (int i = cursor.getCount() - 1; i >= 0; i--) {
					cursor.moveToPosition(i);
					MucChatMsgBean entity = parseCursor(cursor);
					Log.d(TAG, "roomid... " + entity.roomID+" id:"+entity._id+ " content:"+entity.mContent+" platform:"+entity.mPlatForm);
					chatMsgs.add(entity);
				}
			}
			return chatMsgs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeDbAndCursor(cursor);
		}
	}
	/**查询最新的消息**/
	private  MucChatMsgBean queryRoomLastMsgs(String roomid) {
		MucChatMsgBean entity =null;
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_ROOMID
				+ "=?  order by " + _ID + " desc";
		//Log.d(TAG, "queryChatMsgs()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, new String[]{roomid});
			if (cursor != null && cursor.getCount() > 0) {
				if(cursor.moveToFirst()){
					 entity = parseCursor(cursor);
					Log.d(TAG, "roomid... " + roomid+" id:"+entity._id+ " content:"+entity.mContent);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		return entity;
	}
	public ArrayList<MucRoomBean> queryRoomByPlatForm(String platform) {
		ArrayList<MucRoomBean> chatMsgs = new ArrayList<MucRoomBean>();
		//String sql = "select distinct roomid, room,content ,platform from " + TABLE_NAME + " where " + COLOUMN_PlatForm
		//		+ "=?" ;
		Log.d(TAG, "queryRoomByPlatForm()...  "+platform);
				String[] columns={COLOUMN_ROOMID,COLOUMN_RoomName,COLOUMN_CONTENT,COLOUMN_PlatForm,_ID,COLOUMN_CONTENT_TYPE};
		Cursor cursor = null;
		try {
			checkDb();
			//cursor = db.rawQuery(sql, new String[]{platform});
			cursor=db.query(true, TABLE_NAME, columns, COLOUMN_PlatForm+"=?", new String[]{platform}, COLOUMN_ROOMID, null, null, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToLast();
				for (int i = cursor.getCount() - 1; i >= 0; i--) {
					cursor.moveToPosition(i);
					String roomid=cursor.getString(0);
					String room=cursor.getString(1);
					String content=cursor.getString(2);
					String paltform=cursor.getString(3);
					int cid=cursor.getInt(4);
					int contentType=cursor.getInt(5);
					Log.d(TAG, "roomid... " + roomid+" room:"+room+ " content:"+content+" paltform:"+paltform+" cid:"+cid+" contentType:"+contentType);
					MucRoomBean mb=new MucRoomBean(roomid, "0", room);
					MucChatMsgBean lastbean=queryRoomLastMsgs(roomid);
					if(lastbean!=null){
					mb.lastContent=lastbean.mContent;
					mb.lastContentType=contentType;
					}
					chatMsgs.add(mb);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeDbAndCursor(cursor);
		}
		return chatMsgs;
	}
	private MucChatMsgBean parseCursor(Cursor cursor) {
		MucChatMsgBean chatMsg = new MucChatMsgBean();
		chatMsg._id = cursor.getInt(cursor.getColumnIndex(_ID));
		chatMsg.fromUserId = cursor.getString(cursor
				.getColumnIndex(COLOUMN_BAREJID));
		chatMsg.mContent = cursor.getString(cursor
				.getColumnIndex(COLOUMN_CONTENT));
		chatMsg.mContentType = cursor.getInt(cursor
				.getColumnIndex(COLOUMN_CONTENT_TYPE));
		chatMsg.mInsertTime = cursor.getString(cursor
				.getColumnIndex(COLOUMN_INSERT_TIME));
		chatMsg.mUserName = cursor.getString(cursor
				.getColumnIndex(COLOUMN_SENDER));
		chatMsg.roomID = cursor
				.getString(cursor.getColumnIndex(COLOUMN_ROOMID));
		chatMsg.roomName = cursor.getString(cursor
				.getColumnIndex(COLOUMN_RoomName));

		chatMsg.mSendTime = cursor.getString(cursor
				.getColumnIndex(COLOUMN_SEND_TIME));
		chatMsg.mStatus = cursor.getInt(cursor.getColumnIndex(COLOUMN_STATUS));
		chatMsg.mRead = cursor.getInt(cursor.getColumnIndex(COLOUMN_READ));
		chatMsg.mUUID = cursor.getString(cursor.getColumnIndex(COLOUMN_UUID));
		chatMsg.errorCode = cursor.getString(cursor
				.getColumnIndex(COLOUMN_ERRORCODE));
		chatMsg.errorMsg = cursor.getString(cursor
				.getColumnIndex(COLOUMN_ERRORMSG));
		chatMsg.imgPath = cursor.getString(cursor
				.getColumnIndex(COLOUMN_IMGPATH));
		chatMsg.mPlatForm = cursor.getString(cursor
				.getColumnIndex(COLOUMN_PlatForm));
		return chatMsg;
	}

	public boolean deleteOneRoomData(String roomid) {
		try {
			checkDb();
			String whereClause = COLOUMN_ROOMID + " = ?";
			String[] whereArgs = new String[] { roomid };
			int res = db.delete(TABLE_NAME, whereClause, whereArgs);
			return res > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public void deleteAllData() {
		checkDb();
		db.delete(TABLE_NAME, null, null);
	}
}
